<?php
namespace app\admin\controller;

use app\common\model\AccountLog;
use app\common\model\BusInquiry;
use app\common\model\BusInquirySuppliers;
use app\common\model\SalesCompany;
use app\common\model\SysOrder;
use app\common\model\SysUser;
use think\Exception;

/**
 * 财务管理
 * Class Realdata
 * @package app\gygt\controller
 */
class Order extends Admin
{
    /**
     * 获取订单列表
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getList(){
        $page = input('page', 1);
        $limit = input('limit', 20);
        $param = $this->getOrderWhere();

        $model = new BusInquirySuppliers();
        $count = $model->where($param)->count();
        if($page > ceil($count/$limit)){
            $page = ceil($count/$limit);
        }
        $lst = $model->with(['salesCompany','income'])->where($param)->order('sure_datetime desc,id desc')->page($page,$limit)->select();
        foreach ($lst as $item){
            $item['tax'] = round(($item['freight'] + $item['totall_price'])*$item['tax_rate']/100);
            $item['totall_price_tax'] = round($item['freight'] + $item['totall_price'] +$item['tax']);
            $item['returned_diff'] = round($item['totall_price_tax'] - $item['returned_money']);
            $item['total_cost'] = round($item['totall_price_tax'] + $item['repair_company_money'] + $item['loss_assessor_money']);
            $item['sales_totall_price_tax'] = round(($item['sales_freight'] + $item['sales_totall_price'])*(100+$item['sales_tax_rate'])/100);
            $item['sales_returned_diff'] = round($item['sales_totall_price_tax'] - $item['sales_returned_money']);
            $item['profit'] = round($item['sales_returned_money'] - $item['total_cost']);
            $item['profit_rate'] = $item['sales_returned_money']>0?sprintf('%.2f',$item['profit'] / $item['sales_returned_money'] * 100).'%':0;
            $item['plan_profit_rate'] = $item['sales_totall_price_tax']>0?sprintf('%.2f',($item['sales_totall_price_tax']-$item['total_cost']) / $item['sales_totall_price_tax'] * 100).'%':0;
            $item['returned_money_info'] = $item['returned_money_state']==0?'否':($item['returned_money_state']==2?'是(含税点)':'是(含税点) 已付：'.$item['returned_money'].'元');
        }
        return json_tab_msg($count,$page,$lst,'success');
    }
    /**
     * 列表导出
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function orderExport(){
        $param = $this->getOrderWhere();
        $model = new BusInquirySuppliers();
        $order_lst = $model->with(['salesCompany','income'])->where($param)->order('sure_datetime desc,id desc')->select();
        $inquiryModel = new BusInquiry();
        $inquiryModel->orderHandle($order_lst);
    }
    /**
     * 筛选条件
     * @return array
     */
    private function getOrderWhere(){
        $due_date = input('due_date','','trim');
        $bus_from_company_name = input('bus_from_company_name','','trim');
        $bus_to_company_name = input('bus_to_company_name','','trim');
        $car_model = input('car_model','','trim');
        $vehicle_license_num = input('vehicle_license_num','','trim');
        $loss_assessor = input('loss_assessor','','trim');
        $repair_company = input('repair_company','','trim');
        $role_id = input('opt_role_id','');
        $param = [];
        if($role_id == 2){
            $param['add_user_id'] = input('opt_user_id');
        }
        $param['state'] = 6;
        if($due_date){
            $date_arr = explode(' - ',$due_date);
            if(!empty($date_arr)){
                $param['sure_datetime'] = ['between', [trim($date_arr[0]), date('Y-m-d', strtotime ("+1 day", strtotime(trim($date_arr[1]))))]];
            }
        }
        if($bus_from_company_name){
            $param['bus_from_company_name'] = ['like','%'.$bus_from_company_name.'%'];
        }
        if($bus_to_company_name){
            $param['bus_to_company_name'] = ['like','%'.$bus_to_company_name.'%'];
        }
        if($car_model){
            $param['car_model'] = ['like','%'.$car_model.'%'];
        }
        if($vehicle_license_num){
            $param['vehicle_license_num'] = ['like','%'.$vehicle_license_num.'%'];
        }
        if($loss_assessor){
            $param['loss_assessor|loss_assessor_phone'] = ['like','%'.$loss_assessor.'%'];
        }
        if($repair_company){
            $param['repair_company_name|repair_company_phone'] = ['like','%'.$repair_company.'%'];
        }
        return $param;
    }

    /**
     * 获取首页统计数据
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getOrderSum(){
        $role_id = input('opt_role_id','');
        $opt_user_id = input('opt_user_id','');
        $param = [];
        if($role_id == 2){
            $param['add_user_id'] = $opt_user_id;
        }
        $order_model = new BusInquiry();
        $supplier_model = new BusInquirySuppliers();
        $paramY['add_datetime'] = ['>=',date('Y-01-01 00:00:00')];
        // 本年全部新增询价
        $pagobj['year_inquiry_num'] = $order_model->where($param)->where($paramY)->count();
        $paramY['sale_price_state'] = 4;
        $paramY['sure_datetime'] = ['>=',date('Y-01-01 00:00:00')];
        $pagobj['year_order_num'] = $order_model->where($param)->where($paramY)->count();
        $year_sale_info = $order_model->where($param)->where($paramY)->field('sum(returned_money) as sale_returned_money,sum((freight+totall_price)*(100+tax_rate)/100) as sum_able_amount,sum(loss_assessor_money+repair_company_money) as total_cost,sum(loss_assessor_pay+repair_company_pay) as pay_cost')->find();
        $pagobj['year_sale_returned_money'] = $year_sale_info['sale_returned_money']?:0;
        $pagobj['year_sale_able_amount'] = sprintf('%.2f',$year_sale_info['sum_able_amount']);
        unset($paramY['sale_price_state']);
        $paramY['state'] = 6;
        $year_purchase_info = $supplier_model->where($param)->where($paramY)->field('sum((freight+totall_price)*(100+tax_rate)/100) as total_cost,sum(returned_money) as pay_cost')->find();
        $pagobj['year_purchase_total_cost'] = sprintf('%.2f',$year_purchase_info['total_cost']+$year_sale_info['total_cost']);
        $pagobj['year_purchase_pay_cost'] = sprintf('%.2f',$year_purchase_info['pay_cost']+$year_sale_info['pay_cost']);
        // 本月
        $time_start2 = date("Y-m-01", time()).' 00:00:00';
        $time_end2 =  date('Y-m-t', time()).' 23:59:59';
        $paramM['add_datetime'] = ['between', [$time_start2, $time_end2]];
        $pagobj['month_inquiry_num'] = $order_model->where($param)->where($paramM)->count();
        $paramM['sure_datetime'] = ['between', [$time_start2, $time_end2]];
        $paramM['sale_price_state'] = 4;
        $pagobj['month_order_num'] = $order_model->where($param)->where($paramM)->count();
        $month_sale_info = $order_model->where($param)->where($paramM)->field('sum(returned_money) as sale_returned_money,sum((freight+totall_price)*(100+tax_rate)/100) as sum_able_amount,sum(loss_assessor_money+repair_company_money) as total_cost,sum(loss_assessor_pay+repair_company_pay) as pay_cost')->find();
        $pagobj['month_sale_returned_money'] = $month_sale_info['sale_returned_money']?:0;
        $pagobj['month_sale_able_amount'] = sprintf('%.2f',$month_sale_info['sum_able_amount']);
        unset($paramM['sale_price_state']);
        $paramM['state'] = 6;
        $month_purchase_info = $supplier_model->where($param)->where($paramM)->field('sum((freight+totall_price)*(100+tax_rate)/100) as total_cost,sum(returned_money) as pay_cost')->find();
        $pagobj['month_purchase_total_cost'] = sprintf('%.2f',$month_purchase_info['total_cost']+$month_sale_info['total_cost']);
        $pagobj['month_purchase_pay_cost'] = sprintf('%.2f',$month_purchase_info['pay_cost']+$month_sale_info['pay_cost']);
        // 今日新增
        $date = date("Y-m-d");
        $time_start3 = $date.' 00:00:00';
        $time_end3 = $date.' 23:59:59';
        $paramD['state'] = ['<>', 3];
        $paramD['sale_price_state'] = 0;
        $pagobj['today_inquiry_num'] = $order_model->where($param)->where($paramD)->count();
        $paramD['sale_price_state'] = 1;
        $pagobj['today_bid_num'] = $order_model->where($param)->where($paramD)->count();
        $accountLogModel = new AccountLog();
        $sum_pay = $accountLogModel->where($param)->where(['pay_datetime'=>['between',[$time_start3, $time_end3]],'type'=>2])->sum('account');
        $sum_pay1 = $accountLogModel->where($param)->where(['pay_datetime'=>['between', [$time_start3, $time_end3]],'type'=>1,'account'=>['<',0]])->sum('account');
        $pagobj['today_pay_money'] = $sum_pay+(-$sum_pay1);
        $pagobj['today_returned_money'] = $accountLogModel->where($param)->where(['pay_datetime'=>['between', [$time_start3, $time_end3]],'type'=>1,'account'=>['>',0]])->sum('account');;
        json_return_code($pagobj);
    }


    public function getHistogram()
    {
        $role_id = input('opt_role_id','');
        $opt_user_id = input('opt_user_id','');
        $user_id = input('user_id','');
        $type = input('type','');
        $beginDate = input('beginDate','');
        $endDate = input('endDate','');
        $param = [];
        $listRes = [];
        if($role_id == 2){
            $param['add_user_id'] = $opt_user_id;
        }else if($user_id){
            $param['add_user_id'] = $user_id;
        }
        if($type == 1){
            $field = 'substring(pay_datetime,1,4)';
            $curDate = $beginDate;
            while ($curDate <= $endDate){
                $obj['beginDate'] = $curDate;
                $obj['order_return'] = 0;
                $obj['order_pay'] = 0;
                $curDate = $curDate + 1;
                array_push($listRes,$obj);
            }
        }elseif ($type == 2){
            $field = 'substring(pay_datetime,1,7)';
            $curDate = $beginDate;
            while ($curDate <= $endDate){
                $obj['beginDate'] = $curDate;
                $obj['order_return'] = 0;
                $obj['order_pay'] = 0;
                $curDate = date_add(date_create($curDate),date_interval_create_from_date_string("1 months"));
                $curDate = date_format($curDate,"Y-m");
                array_push($listRes,$obj);
            }
        }else{
            $field = 'substring(pay_datetime,1,10)';
            $curDate = $beginDate;
            while ($curDate <= $endDate){
                $obj['beginDate'] = $curDate;
                $obj['order_return'] = 0;
                $obj['order_pay'] = 0;
                $curDate = date_add(date_create($curDate),date_interval_create_from_date_string("1 days"));
                $curDate = date_format($curDate,"Y-m-d");
                array_push($listRes,$obj);
            }
        }

        $order_model = new AccountLog();
        $order_lst = $order_model->field($field.' as beginDate, sum(account) as sum_price,type')->where($field ." BETWEEN '" .$beginDate ."' and '".$endDate."'" )
            ->where($param)->group('beginDate,type')->select();
        foreach ($listRes as &$itemRes){
            foreach ($order_lst as $item){
                if($itemRes["beginDate"] == $item["beginDate"]){
                    if($item['type'] == 1){
                        $itemRes["order_return"] = $item["sum_price"];
                    }else{
                        $itemRes["order_pay"] = $item["sum_price"];
                    }
                }
            }
        }
        $histogram = [
            'xdata' => array_column($listRes, 'beginDate'),
            'order_return' => array_column($listRes, 'order_return'),
            'order_pay' => array_column($listRes, 'order_pay'),
        ];
        json_return_code($histogram);
    }

}
